#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <string>
#include "Log.hpp"

void usage(std::string proc){
    std::cout << "usage is \n\t" << proc << "  client_ip  client_port" << std::endl;
}

int main(int argc, char* argv[]){
    if(argc != 3){
        usage(argv[0]);
        exit(1);
    } 
    //1.0 设置好服务器ip地址和端口号  
    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    //2.0创建套接字
    ssize_t sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0){
        std::cerr << "sockfd is faild \n";
    }
    
    //3，0设置服务端的消息
    sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(ip.c_str());


    while(true){
        std::cout << "请输入你要翻译的单词： " ;
        std::string message;
        std::getline(std::cin, message);
        sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&server, sizeof(server));
        char buffer[1024];

        //4,0设置接收端的消息
        sockaddr_in peer;
        socklen_t len = sizeof(peer);
        ssize_t n = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&peer, &len);

        if(n){
            buffer[n] = 0;
            std::cout << "该单词的中文意思为#:  " << buffer << std::endl; 
        }


    } 
}